package com.bocai.kelala.ui.travel.set.act;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bocai.kelala.App;
import com.bocai.kelala.R;
import com.bocai.kelala.base.BaseActivity;
import com.bocai.kelala.bean.AddressListBean;
import com.bocai.kelala.bean.MyAddressBean;
import com.bocai.kelala.ui.travel.main.act.MainActivity;
import com.bocai.kelala.ui.travel.main.module.MainModule;
import com.bocai.kelala.ui.travel.set.contract.AddAddressContract;
import com.bocai.kelala.ui.travel.set.module.AddAddressModule;
import com.bocai.kelala.ui.travel.set.presenter.AddAddressPresenter;
import com.bocai.kelala.util.DBManager;
import com.bocai.kelala.util.SP;
import com.bocai.kelala.widget.AlertDialog;
import com.bocai.mybase.bean.AddressPortBean;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.SwitchView;

/**
 * Created by yuanfei on 2017/6/12.
 */

public class AddAddressActivity extends BaseActivity implements AddAddressContract.view {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.add_name)
    EditText addName;
    @BindView(R.id.ll_receiver_name)
    LinearLayout llReceiverName;
    @BindView(R.id.add_phone)
    EditText addPhone;
    @BindView(R.id.add_zip_code)
    EditText addZipCode;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.tv_detail_address)
    EditText tvDetailAddress;
    @BindView(R.id.ll_detail_address)
    LinearLayout llDetailAddress;
    @BindView(R.id.address_check)
    SwitchView addressCheck;
    @BindView(R.id.btn_save)
    Button btnSave;
    @BindView(R.id.ll_delete)
    LinearLayout llDelete;
    private DBManager dbM;
    private SQLiteDatabase db;
    public List<MyAddressBean> options1Items = new ArrayList<>();
    public List<List<MyAddressBean>> options2Items = new ArrayList<>();
    public List<List<List<MyAddressBean>>> options3Items = new ArrayList<>();
    private OptionsPickerView<MyAddressBean> mPvOptions;
    private String provinceId,cityId,districtId;
    private String provinceName,cityName,districtName;
    @Inject
    AddAddressPresenter presenter;
    AddressListBean.AddressesBean data;
    private int index = 0;

    @Override
    public int getLayoutId() {
        return R.layout.act_add_address;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new AddAddressModule(this)).inject(this);
    }

    @Override
    public void initView() {
        initToolbar("地址管理");
        initBack(imgBack,llBack);
        data = (AddressListBean.AddressesBean) getIntent().getSerializableExtra("data");
        index = getIntent().getIntExtra("index",0);
        if (index == 1){
            setData();
        }
        new positionAsyn().execute();

        addName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())
                        &&!TextUtils.isEmpty(addZipCode.getText().toString())&&!TextUtils.isEmpty(tvDetailAddress.getText().toString())
                        &&!TextUtils.isEmpty(tvAddress.getText().toString())){
                    btnSave.setEnabled(true);
                    btnSave.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnSave.setEnabled(false);
                    btnSave.setTextColor(getResources().getColor(R.color.text_color));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        addPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())
                        &&!TextUtils.isEmpty(addZipCode.getText().toString())&&!TextUtils.isEmpty(tvDetailAddress.getText().toString())
                        &&!TextUtils.isEmpty(tvAddress.getText().toString())){
                    btnSave.setEnabled(true);
                    btnSave.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnSave.setEnabled(false);
                    btnSave.setTextColor(getResources().getColor(R.color.text_color));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        addZipCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())
                        &&!TextUtils.isEmpty(addZipCode.getText().toString())&&!TextUtils.isEmpty(tvDetailAddress.getText().toString())
                        &&!TextUtils.isEmpty(tvAddress.getText().toString())){
                    btnSave.setEnabled(true);
                    btnSave.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnSave.setEnabled(false);
                    btnSave.setTextColor(getResources().getColor(R.color.text_color));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvDetailAddress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())
                        &&!TextUtils.isEmpty(addZipCode.getText().toString())&&!TextUtils.isEmpty(tvDetailAddress.getText().toString())
                        &&!TextUtils.isEmpty(tvAddress.getText().toString())){
                    btnSave.setEnabled(true);
                    btnSave.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnSave.setEnabled(false);
                    btnSave.setTextColor(getResources().getColor(R.color.text_color));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        addressCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())
                        &&!TextUtils.isEmpty(addZipCode.getText().toString())&&!TextUtils.isEmpty(tvDetailAddress.getText().toString())
                        &&!TextUtils.isEmpty(tvAddress.getText().toString())){
                    btnSave.setEnabled(true);
                    btnSave.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnSave.setEnabled(false);
                    btnSave.setTextColor(getResources().getColor(R.color.text_color));
                }
            }
        });
    }

    public void setData(){
        llDelete.setVisibility(View.VISIBLE);
        addName.setText(data.getContacts());
        addPhone.setText(data.getPhone());
        addZipCode.setText(data.getPostcode());
        tvAddress.setText(data.getRegionName());
        tvDetailAddress.setText(data.getAddress());
        addressCheck.setOpened(data.isIsDefault());
        provinceId = data.getProvince();
        cityId = data.getCity();
        districtId = data.getDistrict();
        llDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDialog();
            }
        });
    }

    @OnClick({R.id.btn_save,R.id.tv_address})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_save:
                if (TextUtils.isEmpty(addName.getText().toString())){
                    showShortToast("请输入收货人姓名");
                }else if (TextUtils.isEmpty(addPhone.getText().toString())){
                    showShortToast("请输入联系电话");
                }else if (addPhone.getText().toString().length()!=11){
                    showShortToast("请正确的电话");
                }else if (TextUtils.isEmpty(tvAddress.getText().toString())){
                    showShortToast("请选择地区");
                }else if (TextUtils.isEmpty(tvDetailAddress.getText().toString())){
                    showShortToast("请输入详细地址");
                }else {
                    AddressPortBean bean = new AddressPortBean();
                    bean.setProvince(provinceId);
                    bean.setCity(cityId);
                    bean.setDistrict(districtId);
                    bean.setAddress(tvDetailAddress.getText().toString());
                    bean.setContacts(addName.getText().toString());
                    bean.setPhone(addPhone.getText().toString());
                    bean.setPostcode(addZipCode.getText().toString());
                    bean.setRegionName(tvAddress.getText().toString());
                    bean.setDefault(addressCheck.isOpened());

                    if (index == 1){
                        presenter.modifyAddress(data.getId(),bean);
                    }else {
                        presenter.addAddress(bean);
                    }
                }
                break;
            case R.id.tv_address:
                mPvOptions.show();
                break;
        }
    }

    public void setAddressSelect() {

        if (options1Items.size() <= 0 || options2Items.size() <= 0 || options3Items.size() <= 0) {
            options1Items.clear();
            options2Items.clear();
            options3Items.clear();
            db = dbM.openDatabase();
            options1Items = findProvince();
            for (MyAddressBean entity : options1Items) {
                List<MyAddressBean> list = findCityOrArea(entity);
                List<List<MyAddressBean>> list3 = new ArrayList<>();
                if (list.size() > 0) {
                    options2Items.add(list);
                } else {
                    list.add(new MyAddressBean("", "", ""));
                    options2Items.add(list);
                }
                for (MyAddressBean cityEntity : list) {
                    List<MyAddressBean> list2 = findCityOrArea(cityEntity);
                    if (list2.size() > 0) {
                        list3.add(list2);
                    } else {
                        list2.add(new MyAddressBean("", "", ""));
                        list3.add(list2);
                    }
                }
                options3Items.add(list3);
            }
//            db.close();
        }

    }


    private ArrayList<MyAddressBean> findProvince() {
        ArrayList<MyAddressBean> provice = new ArrayList<>();

        Cursor cursor = db.rawQuery("SELECT * FROM bnt_districts WHERE ParentId = ?", new String[]{"0"});
        while (cursor.moveToNext()) {
            MyAddressBean entity = new MyAddressBean(cursor.getString(cursor.getColumnIndex("Id")),
                    cursor.getString(cursor.getColumnIndex("ParentId")),
                    cursor.getString(cursor.getColumnIndex("FullName")));

            provice.add(entity);
        }
        cursor.close();
        return provice;
    }


    public OptionsPickerView initPickView() {
        //选项选择器
        OptionsPickerView<MyAddressBean> pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                provinceName = options1Items.get(options1).getFullName();
                provinceId = options1Items.get(options1).getId();
                cityName = options2Items.get(options1).get(options2).getFullName();
                cityId = options2Items.get(options1).get(options2).getId();
                districtName = options3Items.get(options1).get(options2).get(options3).getFullName();
                districtId = options3Items.get(options1).get(options2).get(options3).getId();
                tvAddress.setText(provinceName+" "+cityName+" "+districtName);
                if (!TextUtils.isEmpty(addName.getText().toString())&&!TextUtils.isEmpty(addPhone.getText().toString())
                        &&!TextUtils.isEmpty(addZipCode.getText().toString())&&!TextUtils.isEmpty(tvDetailAddress.getText().toString())
                        &&!TextUtils.isEmpty(tvAddress.getText().toString())){
                    btnSave.setEnabled(true);
                    btnSave.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnSave.setEnabled(false);
                    btnSave.setTextColor(getResources().getColor(R.color.text_color));
                }
            }
        }).build();
        //三级联动效果
        pvOptions.setPicker(options1Items, options2Items, options3Items);
        //设置选择的三级单位
        pvOptions.setSelectOptions(0, 0, 0);

        return pvOptions;

    }

    private ArrayList<MyAddressBean> findCityOrArea(MyAddressBean bean) {
        ArrayList<MyAddressBean> citys = new ArrayList<>();
        Cursor cursor = db.rawQuery("SELECT * FROM bnt_districts WHERE ParentId = ?", new String[]{bean.getId()});
        while (cursor.moveToNext()) {
            MyAddressBean entity = null;
            entity = new MyAddressBean(cursor.getString(cursor.getColumnIndex("Id")),
                    cursor.getString(cursor.getColumnIndex("ParentId")),
                    cursor.getString(cursor.getColumnIndex("FullName")));

            citys.add(entity);
        }
        cursor.close();
        return citys;
    }

    @Override
    public void addAddressSuccess(AddressListBean.AddressesBean bean) {
        if (bean.isIsDefault()){
            SP.put(this,"addressId",bean.getId());
            SP.put(this,"address",bean.getAddress());
            SP.put(this,"name",bean.getContacts());
            SP.put(this,"phone",bean.getPhone());
            SP.put(this,"regionName",bean.getRegionName());
        }

        if (data!=null&&data.isIsDefault()&&!addressCheck.isOpened()){
            SP.put(this,"addressId","");
            SP.put(this,"address","");
            SP.put(this,"name","");
            SP.put(this,"phone","");
            SP.put(this,"regionName","");
        }

        showShortToast("添加成功");
        finish();
    }

    @Override
    public void getAddressList(AddressListBean bean) {

    }

    @Override
    public void deleteAddressSuccess() {
        showShortToast("删除成功");
        finish();
    }

    @Override
    public void modifyAddress() {
        showShortToast("修改成功");
        finish();
    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {

        if (msg.equals("用户授权失败")){
            msg = "您的登录已失效，请重新登录";
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }
        showShortToast(msg);
    }

    public class positionAsyn extends AsyncTask<String,String,String> {
        @Override
        protected void onPreExecute() {
//            showDialog("正在加载");
            startProgressDialog("正在加载");
        }

        @Override
        protected String doInBackground(String... strings) {
            dbM = new DBManager(AddAddressActivity.this);
            setAddressSelect();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            stopProgressDialog();
            mPvOptions = initPickView();
        }
    }
    public void setDialog(){
        new AlertDialog(mContext).builder().setTitle("确定删除收货地址?")
                .setPositiveButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.deleteAddress(data.getId());
            }
        }).show();
    }
}
